# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-07-15 22:58
# File     : model_manager.py
# Project  : dynamic-portfolio-optimizer
# Desc     :

# src/models/model_manager.py
import joblib
import json
from datetime import datetime
from pathlib import Path


class ModelManager:
    """模型管理器"""

    def __init__(self, model_dir="models"):
        self.model_dir = Path(model_dir)
        self.model_dir.mkdir(exist_ok=True)

    def save_model(self, model, model_name, metadata=None):
        """保存模型"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        model_path = self.model_dir / f"{model_name}_{timestamp}.pkl"

        # 保存模型
        joblib.dump(model, model_path)

        # 保存元数据
        if metadata:
            metadata_path = model_path.with_suffix('.json')
            with open(metadata_path, 'w') as f:
                json.dump(metadata, f, indent=2)

        return str(model_path)

    def load_latest_model(self, model_name):
        """加载最新模型"""
        model_files = list(self.model_dir.glob(f"{model_name}_*.pkl"))

        if not model_files:
            raise FileNotFoundError(f"未找到模型: {model_name}")

        # 获取最新的模型文件
        latest_model = max(model_files, key=lambda x: x.stat().st_mtime)

        return joblib.load(latest_model)

